import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as mqtt from 'mqtt'
@Injectable()
export class MqttService {
    private client:mqtt.MqttClient;
    private chargeTopic:string;
    private addChargeTopic:string;
    private stopChargeTopic:string;

    constructor(
        private configService:ConfigService
    ) {
        this.connect()
    }

    connect() :Promise<void>{
        const conf = this.configService.get('mqtt')

        this.chargeTopic = conf.topic.charge
        this.addChargeTopic = conf.topic.addCharge
        this.stopChargeTopic = conf.topic.stopCharge

        return new Promise((resolve, reject) => {
            this.client = mqtt.connect(conf.options)
            this.client.on('disconnect', () => {
                console.log('mqtt重连')
                this.client.reconnect()
            }).on('error', error => {
                reject(error)
            }).on('connect', () => {
                resolve()
            })
        })

        
    }

    publish(topic:string, params:Object) {
        this.client.publish(topic, JSON.stringify(params), {
            qos : 2
        })
    }
}
